<template>
  <TextSetting :data="data" :disabled="disabled">
    <ElFormItem prop="dateFormat" label="日期格式">
      <ElSelect v-model="dateFormat" popper-class="fa-contract-scope" :disabled="disabled">
        <ElOption v-for="{ label, value } in DateFormatList" :key="value" :value="value" :label="label" />
      </ElSelect>
    </ElFormItem>

    <ElFormItem prop="value" label="默认日期">
      <ElDatePicker
        v-model.trim="data.value"
        :disabled="disabled"
        :format="formatter.format"
        :value-format="formatter.format"
        :placeholder="formatter.label"
      />
    </ElFormItem>
  </TextSetting>
</template>

<script lang="ts">
import { defineComponent, ref, toRef, watch } from 'vue'
import { Widget } from '@/models'
import { DateFormatList } from '@/types'
import useDateFormat from './useDateFormat'
import formatDateString from './formatDateString'
import TextSetting from '../input/TextSetting.vue'

export default defineComponent({
  name: 'FaDateFillSetting',

  components: { TextSetting },

  props: {
    /** 控件数据 */
    data: {
      type: Widget,
      required: true
    },

    /** 是否禁用 */
    disabled: {
      type: Boolean,
      default: false
    }
  },

  setup(props) {
    const data = toRef(props, 'data')

    /** 日期格式 */
    const dateFormat = ref(data.value.dateFormat)

    /**
     * 格式更改后更新值
     * 避免 ElDatePicker 格式更改后值不更新并报错
     */
    watch(dateFormat, async format => {
      const widget = data.value
      let val = widget.value as string

      if (val) {
        widget.value = formatDateString(val, format)
      }

      widget.dateFormat = format
    })

    return {
      formatter: useDateFormat(data),

      /** 日期格式 */
      dateFormat,

      DateFormatList
    }
  }
})
</script>

<style lang="scss">
.fa-widget-setting .el-date-editor.el-date-editor {
  width: 100%;
}
</style>
